const Router = require('koa-router')
const { resolve } = require('path')
const glob = require('glob')
const pathPrefix = Symbol('pathPrefix')
const routerMap = []
const middlewareArr = []
let router = new Router()
export class Route {
    constructor(app, routesPath) {
        this.app = app
        this.router = router
        this.routesPath = routesPath
    }

    init() {
        const { app, router, routesPath } = this
        glob.sync(resolve(routesPath, './*.js')).forEach(require)
        routerMap.forEach((item, index) => {
            let { target, method, path, callback } = item
            middlewareArr.forEach((item, index) => {
                let {methods, paths, callbacks} = item
                if (methods === method && paths === path) {
                    callback.unshift(callbacks)
                }
            })
            let prefix = target[pathPrefix] ? target[pathPrefix] : ''
            router[method](prefix + path, ...callback)
        })
        app.use(router.routes())
        app.use(router.allowedMethods())
    }
}


function setRouter(method) {
    return function (path) {
        return function (target, key, descriptor) {
            routerMap.push({
                target,
                method,
                path: path,
                callback: [target[key]]
            })
            
        }
    }
}

const middleware = methods => {
    return (paths) => {
        return (target, key, descriptor) => {
            middlewareArr.push({
                methods,
                paths,
                callbacks: target[key]
            })
        }
    }
}


export const Controller = function (path) {
    return function (target) {
        target.prototype[pathPrefix] = path
    }
}

export const Get = setRouter('get')

export const Post = setRouter('post')

export const use = setRouter('use')

export const middlewareGet = middleware('get')

export const middlewarePost = middleware('post')

export const route = router